package org.light4admin.modules.system.controller;

import org.apache.commons.lang3.StringUtils;
import org.light4admin.common.base.BaseController;
import org.light4admin.common.Constants;
import org.light4admin.common.base.Response;
import org.light4admin.modules.system.domain.SysUser;
import org.light4admin.modules.system.domain.vo.LoginUser;
import org.light4admin.modules.system.service.ISysUserService;
import org.light4admin.modules.system.service.impl.TokenService;
import org.light4admin.modules.system.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author light4admin
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;


    /**
     * 个人信息
     */
    @GetMapping
    public Response<Map> profile() {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("roleGroup", userService.selectUserRoleGroup(username));
        dataMap.put("postGroup", userService.selectUserPostGroup(username));
        dataMap.put("user", user);
        return Response.success(dataMap);
    }

    /**
     * 修改用户
     */
    @PutMapping
    public Response<Void> updateProfile(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && Constants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return Response.failed("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && Constants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return Response.failed("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(user) > 0) {
            LoginUser loginUser = tokenService.getLoginUser();
            // 更新缓存用户信息
            loginUser.getSysUser().setNickName(user.getNickName());
            loginUser.getSysUser().setPhonenumber(user.getPhonenumber());
            loginUser.getSysUser().setEmail(user.getEmail());
            loginUser.getSysUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return Response.success();
        }
        return Response.failed("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public Response<Void> updatePwd(String oldPassword, String newPassword) {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return Response.failed("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return Response.failed("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            LoginUser loginUser = tokenService.getLoginUser();
            loginUser.getSysUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return Response.success();
        }
        return Response.failed("修改密码异常，请联系管理员");
    }

//    /**
//     * 头像上传
//     */
//    @PostMapping("/avatar")
//    public Response<Void> avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
//        if (!file.isEmpty()) {
//            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//            R<SysFile> fileResult = remoteFileService.upload(file);
//            if (CollectionUtils.isEmpty(fileResult) || Objects.isNull(fileResult.getData())) {
//                return Response.failed("文件服务异常，请联系管理员");
//            }
//            String url = fileResult.getData().getUrl();
//            if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", url);
//                // 更新缓存用户头像
//                loginUser.getSysUser().setAvatar(url);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
//        }
//        return Response.failed("上传图片异常，请联系管理员");
//    }
}
